import React from 'react';
import {Select, Form, Row, Col, Input, Button, DatePicker, Icon, Cascader, message} from 'antd';
import {withRouter} from 'react-router-dom';
import {chargeTypeJson, stubGpTypeJson} from '../../utils/tranStartType'
import axios from 'axios';
import {sessionManager} from '../../utils/sessionStorage';
import StubPicker from '../../components/pickCity/StubPicker'
import {injectIntl} from 'react-intl';
import options from '../../components/areaPicker/areaPickerOption';
import moment from 'moment';
import qs from 'qs'


const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const FormItem = Form.Item;
const createForm = Form.create;

@withRouter
class historyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      stubGroup: [],
      orderSummary: {},
      searchQuest: "",
      hideFlag: false
    };
    this.formItem = null;
    this.lessXXl=window.innerWidth< 1600;
  }


  componentWillMount() {
    let locale = sessionManager.get('locale');
    this.state.searchQuest = `${qs.stringify(this.props.params)}&locale=${locale}`;
    this.getStuGroup();
    this.getOrderSummary();
  }

  generateAreaOptions () {
    if (this.options) {
      return this.options;
    } else {
      this.options =  options(!0);
      return this.options;
    }
  }


  hideFormItem=(flag)=>{
    this.formItem = document.querySelector('.ant-row-flex');
    if (this.lessXXl) {
      Array.from(this.formItem.children).map((k, v, arr) => {
        if(v>arr.length-7&&v!=arr.length-1)
          flag?k.classList.add('hide'):k.classList.remove('hide');
        if(v==arr.length-1){
          if(flag){
            k.classList.remove('ant-col-xl-19');
            k.classList.add('ant-col-xl-24');
          }else{
            k.classList.remove('ant-col-xl-24');
            k.classList.add('ant-col-xl-19');
          }
        }
      })
    }
  }

  componentDidMount = () => {
    //初始化隐藏表格
    this.hideFormItem(this.state.hideFlag)
  }

  getOrderSummary = (data = this.props.params) => {
    const emptySum = {
      totalPower: 0,
      totalElectric: 0,
      totalService: 0,
      totalFee: 0
    };
    axios.post('/api/order/orderHisSum', {...data}).then(res => {
      if (res && res.code === '200') {
        let summary = {};
        if (res.data) {
          summary = res.data[0] ? res.data[0] : emptySum;
        } else {
          summary = emptySum;
        }
        this.setState(Object.assign(this.state.orderSummary, summary));
      } else {
        this.setState(Object.assign(this.state.orderSummary, emptySum));
      }
    })
  }

  getStuGroup = () => {
    axios.post('/api/stubGroup/listForOption/qry', {}).then(res => {
      if (res && res.data) {
        this.setState({stubGroup: res.data})
      }
    })
  }

  endTimeLess = (rule, value, callback) => {
    let startTime;
    let endTime;
    let differDay;
    if (value && value.length > 0) {
      startTime = value[0].format('x');
      endTime = value[1].format('x');
      differDay = ((endTime - startTime) / 1000 / 60 / 60 / 24);
    }
    if (differDay > 31) {
      callback('相距不能超过31天');
    } else {
      callback();
    }
  }
  //清空表格
  handleReset = () => {
    const {setFieldsValue} = this.props.form;
    this.props.form.resetFields();
    setFieldsValue({
      "validFlag": undefined
    })
  }

  obj2getParam = (values) => {
    var params = ``;
    for (let key of Object.keys(values)) {
      if (values[key]) {
        console.log(key, values[key]);
        params += `${key}=${values[key]}&`
      }
    }
    this.setState({
      searchQuest: params
    })
  }

  //提交表格验证
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (!!errors) {
        console.log('Errors in form!!!');
        return;
      }
      console.log('Submit!!!');
      let data = {
        qryType: 2,
      };
      // values.stubGroupId=values.stubGroupId.currency;
      if (values.searchTimes.length != 0) {
        data.searchTimeStart = values.searchTimes[0].format('YYYY.MM.DD');
        data.searchTimeEnd = values.searchTimes[1].format('YYYY.MM.DD');
      }
      if (values.city.length !== 0) {
        data.city = values.city[values.city.length - 1];
      }
      if (values.appkey) {
        data.appkey = values.appkey.currency;
      }
      delete values['searchTimes'];
      delete values['city'];
      delete values['appkey'];
      Object.assign(values, data);
      // console.log({...values});
      this.obj2getParam(values)
      this.props.formSubmit(values);
      this.getOrderSummary(values);
    });
  }

  changeFlag = () => {
    this.setState({
      hideFlag: !this.state.hideFlag
    },()=>{this.hideFormItem(this.state.hideFlag)})
  }

  download=()=>{
    //searchTimes
    debugger;
    var value=this.props.form.getFieldValue('searchTimes');
    let startTime;
    let endTime;
    let differDay;
    if(value&&value.length===2){
      startTime = value[0].format('x');
      endTime = value[1].format('x');
      differDay = ((endTime - startTime) / 1000 / 60 / 60 / 24);
      if(differDay>31){
        message.error('下载文件时间不能超过31天')
        return
      }
    }
    const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
    let url=`${axios.defaults.baseURL}/api/order/orderHisList/export?${this.state.searchQuest}&token=${token}`;
    window.location.href=url;
  }

  //报表导出按钮
  render() {
    const {getFieldDecorator} = this.props.form;
    const dateFormat = 'YYYY.MM.DD';
    //下拉框校验
    const config = {
      initialValue: [moment(this.props.params.searchTimeStart, dateFormat), moment(this.props.params.searchTimeEnd, dateFormat)]
    };
    const requiredConfig = {
      rules: [
        {
          type: 'string',
          required: !1,
          message: '请输入内容'
        }
      ]
    }
    const gridStyle = {
      width: '20%',
      textAlign: 'center',
      marginBottom: '40px',
      display: 'inline-block'
    };
    const common = this.props.intl.messages.common;
    const validFlag = [
      {name: common.valid, key: 1},
      {name: common.Invalid, key: 2}
    ];
    const disabledDate = function (current) {
      return current && current > moment().subtract(1, 'days') || (current && current > moment().add('days'));
    };

    return (
      <div>
        <form form={this.props.form} className="SC-form">
          <Row gutter={24} type="flex">
            <Col xxl={4} xl={6}>
              <FormItem
                label={common.orderNO}
              >
                {getFieldDecorator('id', requiredConfig)(
                  <Input type={'text'} style={{width: '100%'}} placeholder={common.phOrderNo}/>
                )}
              </FormItem>
            </Col>
            <Col xxl={4} xl={6}>
              <FormItem
                label={common.chargeType}
              >
                {getFieldDecorator('chargeType', {
                  initialValue: ''
                })(
                  <Select  allowClear={true}>
                    {
                      chargeTypeJson.map((item) =>
                        <Option value={item.status} key={item.status}>{item.name}</Option>
                      )
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col xxl={4} xl={8} xs={6}>
              <FormItem
                label={common.chargeMethod}
              >
                {getFieldDecorator('appkey')(
                  <StubPicker useType={'appkey'} url="/api/order/getAppKey"/>
                )}
              </FormItem>
            </Col>
            <Col xxl={4} xl={6}>
              <FormItem
                label={common.stubGroupName}
              >
                {getFieldDecorator('stubGroupName', requiredConfig)(
                  <Input type={'text'} placeholder={common.phstubGpName}/>
                )}
              </FormItem>
            </Col>
            <Col xxl={4} xl={8}>
              <FormItem
                label={common.stubGpPosition}
              >
                {getFieldDecorator('city', {initialValue: []})(
                  <Cascader options={this.generateAreaOptions.bind(this)()} changeOnSelect placeholder={common.phPickArea}/>
                )}
              </FormItem>
            </Col>
            <Col xxl={4} xl={7}>
              <FormItem
                label={common.stubNo}
              >
                {getFieldDecorator('stubId', requiredConfig)(
                  <Input type={'text'} placeholder={common.phStubNo}/>
                )}
              </FormItem>
            </Col>
            <Col xxl={6} xl={8}>
              <FormItem
                label={common.chargingTimeRange}
              >
                {getFieldDecorator('searchTimes', config)(
                  <RangePicker allowClear={false} format="YYYY-MM-DD" style={{width: '100%'}} disabledDate={disabledDate}/>
                )}
              </FormItem>
            </Col>
            <Col xxl={3} xl={4}>
              <FormItem
                label={common.stubGpType}
              >
                {getFieldDecorator('stubGroupType', {
                  initialValue: ''
                })(
                  <Select  allowClear={true}>
                    {
                      stubGpTypeJson.map((item) =>
                        <Option value={item.status} key={item.status}>{item.name}</Option>
                      )
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col xxl={14} xl={8}>
              <FormItem>
                {/*<Button className="ant-btn-84" onClick={this.handleReset}>{common.clear}</Button>*/}
                <Button style={{marginRight: 8}} className="ant-btn-84" type="primary"
                        onClick={this.handleSubmit}>{common.search}</Button>
                <Button onClick={this.download} type="primary" style={{marginRight: 8}}
                        className="ant-btn-84">{common.exportExcel}</Button>
              </FormItem
              >
            </Col>
          </Row>
          <div className="boxTips">
            {/*<p>注：建议查询时选择的充电结束时间段在属于同一个月份</p>*/}
            {/*<p>注：最多只能导出31天的数据</p>*/}
          </div>
          <div className="boxOuter">
            <div className="box box-4">
              <div className="num">{this.state.totalPower}</div>
              <div>{common.charginAmountHis}</div>
            </div>
            <div className="box box-4">
              <div>
                <div className="num">{this.state.totalElectric}</div>
                <div>{common.energyCharge}</div>
              </div>
            </div>
            <div className="box box-4">
              <div>
                <div className="num">{this.state.totalService}</div>
                <div>{common.serviceCharge}</div>
              </div>
            </div>
            <div className="box box-4">
              <div>
                <div className="num">{this.state.totalFee}</div>
                <div>{common.totalChargeCost}</div>
              </div>
            </div>
          </div>
        </form>
      </div>
    )
  }
}

//ant 表格验证需要创建表格-createForm
historyForm = createForm()(historyForm);
export default injectIntl(historyForm);